package com.xbongbong.paas.help;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataDeleteBatchDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.service.PaasFormDataService;
import com.xbongbong.paas.service.WorkflowOperatorDataService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.domain.entity.LabelEntity;
import com.xbongbong.pro.enums.PackageStatusEnum;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.help.SaveFormatHelp;
import com.xbongbong.saas.model.ContactModel;
import com.xbongbong.saas.model.LabelModel;
import com.xbongbong.saas.model.SupplierContactModel;
import com.xbongbong.saas.service.ListBatchService;
import com.xbongbong.saas.service.toolbox.help.PackageStatusHelp;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Component
public class PaasFormDataHelper {
    @Resource
    private PackageStatusHelp packageStatusHelp;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private LabelModel labelModel;
    @Resource
    private WorkflowOperatorDataService workflowOperatorDataService;
    @Resource
    private ContactModel contactModel;
    @Resource
    private SupplierContactModel supplierContactModel;
    @Resource
    private PaasFormDataService paasFormDataService;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private ListBatchService listBatchService;
    @Resource
    private UserModel userModel;

    @Async(value = "addUpdateDelThreadPool")
    public void batchEditContact(SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo, UserVO loginUser, String creatorId, String corpid, Long dataId, String name, Integer isImport, String attr, XbbRefTypeEnum xbbRefTypeEnum) throws XbbException {

        List<ValidateDataDTO> needAddValidateDataDTO = null;
        if (saasNeedRedundantAttrPoJo != null) {
            needAddValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedAddValidateDataDTO();
            for (ValidateDataDTO validateDataDTO : needAddValidateDataDTO) {
                validateDataDTO.setProcessCreatorId(creatorId);
            }
        }
        if (!Objects.isNull(needAddValidateDataDTO)) {
            if (Objects.nonNull(needAddValidateDataDTO) && !needAddValidateDataDTO.isEmpty() && !Objects.equals(needAddValidateDataDTO.get(0).getIsImport(), BasicConstant.ONE)) {
                //非导入时判断数据量限制
                Integer oneStatus = packageStatusHelp.getPackageStatus(corpid, ValueAddedTypeEnum.ONE_FORM_DATA_NUM, needAddValidateDataDTO.size(), xbbRefTypeEnum, needAddValidateDataDTO.get(0).getFormId());
                Integer allStatus = packageStatusHelp.getPackageStatus(corpid, ValueAddedTypeEnum.TOTAL_FORM_DATA_NUM, needAddValidateDataDTO.size());
                if ( !Objects.equals(oneStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(oneStatus, PackageStatusEnum.WARNING.getCode()) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.SINGLE_TABLE_NUM_LIMIT);
                }

                if ( !Objects.equals(allStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(allStatus, PackageStatusEnum.WARNING.getCode()) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.TOTAL_TABLE_NUM_LIMIT);
                }
            }
            String labelAttr = null;
            Map<String, Long> labelPojoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(needAddValidateDataDTO) && !needAddValidateDataDTO.isEmpty() && Objects.equals(needAddValidateDataDTO.get(0).getIsImport(), BasicConstant.ONE)) {
                PaasFormExplainEntity contactExplain = paasFormExplainModel.getByBusinessType(xbbRefTypeEnum.getCode(), needAddValidateDataDTO.get(0).getCorpid());
                List<FieldAttrEntity> explainList = JSONArray.parseArray(contactExplain.getExplains(), FieldAttrEntity.class);
                for (FieldAttrEntity item : explainList) {
                    if (Objects.equals(item.getFieldType(), FieldTypeEnum.LABEL.getType())) {
                        labelAttr = item.getAttr();
                    }
                }

                if (StringUtil.isNotEmpty(labelAttr)) {
                    Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    param.put("formId", contactExplain.getFormId());
                    param.put("corpid", contactExplain.getCorpid());
                    param.put("appId", contactExplain.getAppId());
                    param.put("del", DelEnum.NORMAL.getDel());
                    List<LabelEntity> entitys = labelModel.findEntitys(param);
                    entitys.forEach(item -> {
                        labelPojoMap.put(item.getName(), item.getId());
                    });
                }
            }


            for ( ValidateDataDTO validateDataDTO : needAddValidateDataDTO ) {
                if (Objects.isNull(validateDataDTO.getSerialNo())){
                    validateDataDTO.setSerialNo("");
                }
                JSONObject data = validateDataDTO.getData();
                if ( data.isEmpty() ) {
                    continue;
                }

                if (StringUtil.isNotEmpty(labelAttr)){
                    JSONArray jsonArray = new JSONArray();
                    if (data.get(labelAttr) instanceof  String){
                        if (Objects.nonNull(data.get(labelAttr))){
                            String[] split = data.getString(labelAttr).split(",");
                            for (String s : split) {
                                if (Objects.nonNull(labelPojoMap.get(s))) {
                                    jsonArray.add(labelPojoMap.get(s));
                                }
                            }
                        }
                        data.put(labelAttr, jsonArray);
                    }
                }
                // 把关联客户id塞进去
                data.put(attr, dataId);
                if (Objects.equals(XbbRefTypeEnum.CONTACT.getCode(), xbbRefTypeEnum.getCode())) {
                    data.put(ContactEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), name);
                } else if (Objects.equals(XbbRefTypeEnum.SUPPLIER_CONTACT.getCode(), xbbRefTypeEnum.getCode())) {
                    data.put(SupplierContactEnum.SUPPLIER_ID_LINK_TEXT.getAttr(), name);
                }
                SaveFormatHelp.dealLabelData(validateDataDTO.getData(), validateDataDTO.getExplainMap());
                FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
                BeanUtil.copyProperties(validateDataDTO, formDataAddDTO);

                UserEntity creator = userModel.getByKey(creatorId, corpid);
                UserVO userVO = new UserVO();
                BeanUtil.copyProperties(creator, userVO);

                formDataAddDTO.setLoginUser(userVO);
                formDataAddDTO.setDataList(data);
                PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formDataAddDTO.getFormId(), formDataAddDTO.getCorpid());
                if ( paasFormEntityExt == null ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                }
                PaasFormExplainEntity explainEntity = paasFormExplainModel.getByFormId(validateDataDTO.getFormId(), validateDataDTO.getCorpid());
                Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explainEntity.getExplains(), null);
                // 流水号开启严控模式
                FieldAttrEntity fieldAttrEntity = explainMap.get(FieldTypeEnum.SERIALNO.getAlias());
                if (Objects.nonNull(fieldAttrEntity) && Objects.equals(fieldAttrEntity.getStrictController(), BasicConstant.ONE)) {
                    FormDataAddDTO formDataSaveDTO = new FormDataAddDTO();
                    BeanUtil.copyProperties(validateDataDTO, formDataSaveDTO);
                    formDataSaveDTO.setFormId(formDataAddDTO.getFormId());
                    formDataAddDTO.getDataList().put(FieldTypeEnum.SERIALNO.getAlias(),formDataSaveDTO.getSerialNo());
                    formDataAddDTO.setSerialNo(formDataSaveDTO.getSerialNo());
                }

                formDataAddDTO.setIsImport(isImport);
                formDataAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                formDataAddDTO.setUserId(userVO.getUserId());
                formDataAddDTO.setLoginUserName(userVO.getName());
                formDataAddDTO.setOwnerId(validateDataDTO.getOwnerIds());
                formDataAddDTO.setFromApproval(true);
                // 新建
                workflowOperatorDataService.add(formDataAddDTO);
            }
        }
    }



    @Async(value = "addUpdateDelThreadPool")
    public void batchEditContactForUpdate(SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo, UserVO loginUser, String creatorId, String corpid, Long dataId, String name, Integer isImport, String attr, XbbRefTypeEnum xbbRefTypeEnum) throws XbbException {
        if (Objects.isNull(saasNeedRedundantAttrPoJo)) {
            return;
        }

        List<ValidateDataDTO> needAddValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedAddValidateDataDTO();
        List<ValidateDataDTO> needDelValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedDelValidateDataDTO();
        List<ValidateDataDTO> needUpdateValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedUpdateValidateDataDTO();

        // 更新
        if (CollectionsUtil.isNotEmpty(needUpdateValidateDataDTO)) {
            for ( ValidateDataDTO validateDataDTO : needUpdateValidateDataDTO ) {
                JSONObject data = validateDataDTO.getData();
                if ( data.isEmpty() ) {
                    continue;
                }
                // 把关联客户id塞进去
                data.put(attr, dataId);
                FormDataUpdateDTO formDataUpdateDTO = new FormDataUpdateDTO();
                BeanUtil.copyProperties(validateDataDTO, formDataUpdateDTO);
                formDataUpdateDTO.setOwnerId(validateDataDTO.getOwnerIds());
                formDataUpdateDTO.setDataList(data);
                PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
                BeanUtil.copyProperties(formDataUpdateDTO, paasFormDataEntity);
                paasFormDataEntity.setId(formDataUpdateDTO.getDataId());
                PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formDataUpdateDTO.getFormId(), formDataUpdateDTO.getCorpid());
                if ( paasFormEntityExt == null ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                }
                if ( formDataUpdateDTO.getDataList() != null ) {
                    paasFormDataEntity.setData(formDataUpdateDTO.getDataList());
                }
                paasFormDataEntity.setMenuId(paasFormEntityExt.getMenuId());
                paasFormDataEntity.setCreatorId(formDataUpdateDTO.getUserId());
                if ( Objects.nonNull(formDataUpdateDTO.getOwnerId()) && !formDataUpdateDTO.getOwnerId().isEmpty() ) {
                    paasFormDataEntity.setOwnerId(Objects.toString(formDataUpdateDTO.getOwnerId().get(0).getId(), ""));
                }

                formDataUpdateDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                paasFormDataService.update(formDataUpdateDTO);


//                PaasFormDataEntity oldPaasFormDataEntity = proModelService.getOldPaasFormDataEntity(formDataUpdateDTO);
//                Integer noApprovalRequired = 1;
//                if ( paasFormEntityExt.getIsProcessForm().equals(1) && !Objects.equals(formDataUpdateDTO.getIsImport(), 1) ) {
//                    StartProcessDTO startProcessDTO = new StartProcessDTO();
//                    BeanUtil.copyProperties(formDataUpdateDTO, startProcessDTO);
//                    startProcessDTO.setOwnerId(paasFormDataEntity.getOwnerId());
//                    startProcessDTO.setData(formDataUpdateDTO.getDataList());
//                    startProcessDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
//                    startProcessDTO.setFormDataId(formDataUpdateDTO.getDataId());
//                    startProcessDTO.setCreatorId(formDataUpdateDTO.getUserId());
//                    startProcessDTO.setBusinessType(xbbRefTypeEnum.getCode());
//                    StartProcessVO startProcessVO = processStartHelp.startProcess(startProcessDTO, oldPaasFormDataEntity);
//                    if ( Objects.isNull(startProcessVO) ) {
//                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.START_PROCESS_ERROR);
//                    }
//                    noApprovalRequired = startProcessVO.getNoApprovalRequired();
//                }
//                if(noApprovalRequired.equals(1)){
//                    proModelService.update(formDataUpdateDTO, paasFormDataEntity, oldPaasFormDataEntity, paasFormEntityExt);
//                }else {
//                    PaasProcessDataEntity paasProcessDataEntity = new PaasProcessDataEntity();
//                    paasProcessDataEntity.setCorpid(formDataUpdateDTO.getCorpid());
//                    paasProcessDataEntity.setFormDataId(oldPaasFormDataEntity.getId());
//                    paasProcessDataEntity.setBusinessType(XbbRefTypeEnum.CONTACT.getCode());
//                    paasProcessDataEntity.setSaasMark(formDataUpdateDTO.getSaasMark());
//                    proModelService.updateFormDataStatus(paasProcessDataEntity, FlowStatusEnum.IN_APPROVAL.getType());
//                }
            }
        }

        // 删除
        if (CollectionsUtil.isNotEmpty(needDelValidateDataDTO)) {
            List<Long> delDataId = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for ( ValidateDataDTO needDelDTO : needDelValidateDataDTO ) {
                Long id = needDelDTO.getDataId();
                if ( id != null ) {
                    delDataId.add(id);
                }
            }
            //未开启工作流直接删除
            if(!commonHelp.isOpenWorkFlow(corpid)){
                switch (xbbRefTypeEnum) {
                    case CONTACT:
                        contactModel.deleteBatch(delDataId, corpid, WriteRequest.RefreshPolicy.NONE);
                        break;
                    case SUPPLIER_CONTACT:
                        supplierContactModel.deleteBatch(delDataId, corpid);
                        break;
                    default:
                }
            }else{
                FormDataDeleteBatchDTO formDataDeleteBatchDTO = new FormDataDeleteBatchDTO();
                ValidateDataDTO validateDataDTO = needDelValidateDataDTO.get(0);
                BeanUtil.copyProperties(validateDataDTO, formDataDeleteBatchDTO);
                formDataDeleteBatchDTO.setDataIdList(delDataId);
                formDataDeleteBatchDTO.setIsSkipPermissionCheck(BasicConstant.ONE);
                listBatchService.deleteBatch(formDataDeleteBatchDTO);
            }

        }

        // 新建
        if (CollectionsUtil.isNotEmpty(needAddValidateDataDTO)) {
            batchEditContact(saasNeedRedundantAttrPoJo, loginUser, creatorId, corpid, dataId, name, isImport, attr, xbbRefTypeEnum);
        }

    }
}
